package com.itheima.health.task;
/*
 *@description  清理垃圾图片的定时任务
 com.itheima.health.task
 *@create 2023/9/3 
*/

import com.itheima.health.common.RedisConstant;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;

@Component
@Slf4j
public class ClearImgTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QiniuUtils qiniuUtils;


    @Scheduled(cron = "0 0 12 * * ?")
    //@Scheduled(cron = "0/10 * * * * ?")
    public void clearImg() {
        // 根据redis中保存的两个set集合进行差值计算,获得垃圾图片名称集合
        log.info("垃圾图片开始清理了~~~");
        Set diffSets = this.redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        if (!CollectionUtils.isEmpty(diffSets)) {

            for (Object picName : diffSets) {
                // 删除七牛云服务器上的图片
                this.qiniuUtils.deleteFileFromQiniu((String) picName);
                // 从Redis集合中删除图片名称
                this.redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, picName);
            }
        }

    }
}
